<?php

if (!defined('BASEPATH'))
    exit('No direct script access allowed');

class Reserva extends CI_Controller {
    
    public $ruta_template;
    public $fields_table;
    public $fields_form;
    public $validate_fields;

    function __construct(){
        parent::__construct();
        if($this->session->userdata('idusuario') == null){show_404();}
        $this->lang->load('lang/res_'.$this->config->item('language'), $this->config->item('language'));
        $this->load->model('reserva_model');
        $this->load->library('form_validation');
        $this->ruta_template = array('ruta' => site_url().'public/'.$this->template->getActiveTemplate());
        $this->template->write_view('footer', 'footer');
        $this->template->write_view('header', 'header');
        $this->template->write_view('_scripts', 'js', $this->ruta_template);
        $this->template->write_view('_styles', 'css', $this->ruta_template);
        $this->fields_table = array('', 'res_idreserva', 'res_fechadesde', 'res_fechahasta', 'res_nombrecliente',
            'res_numeropersonas', 'res_importefianza, res_importetotal');
        $this->fields_form = array('res_idreserva', 'res_fechadesde', 'res_fechahasta', 'res_nombrecliente',
            'res_emailcliente', 'res_telefonocliente', 'res_numeropersonas', 'res_importefianza', 'res_importetotal', 'res_observaciones');
        $this->validate_fields = array('', 'trim|required', 'trim|required', 'trim|required', 'trim|required');
    }

    public function getTemplate(){
        $row = '<tr value="%TABLEID%" bgcolor="white">';
        return array ('table_open'  => '<table id="tabla">', 'row_start'  => $row, 'row_alt_start'  => $row);
    }
    
    public function ver($idreserva = ''){
        $this->session->set_userdata(array('tab_sel' => 'tarifas'));
        $this->load->library('table');
        $this->load->library('form_creator');
        $data['idproducto'] = $this->reserva_model->getIdProducto($idreserva);
        if($data['idproducto'] == null){
            show_404();
        }
        $reserva = $this->reserva_model->getReservas($this->fields_form, $idreserva);
        $this->form_creator->setTabla(strtolower(__CLASS__));
        $row = $reserva->row_array();
        $hidden  = $this->form_creator->pintaCampo(array('field' => $this->fields_form[0], 'type' => 'HDN', 'value' => $row[$this->fields_form[0]]));
        $hidden .= $this->form_creator->pintaCampo(array('field' => "p_accion", 'type' => 'HDN', 'value' => 'E'));
        $hidden .= $this->form_creator->pintaCampo(array('field' => "p_campos", 'type' => 'HDN', 'value' => $idreserva));
        $campos = array();
        for($x = 1; $x < count($this->fields_form); $x++){
            $campos[] = "<b>".lang($this->fields_form[$x]).": </b>";
            $campos[] = $this->form_creator->pintaCampo(array('field' => $this->fields_form[$x], 'type' => 'TXT', 'value' => $row[$this->fields_form[$x]]));
        }
        $new_list = $this->table->make_columns($campos, 4);
        $data['tabla'] = $hidden.$this->table->generate($new_list, strtolower(__CLASS__));
        
        $this->template->write_view('content', 'content/reserva_ver', $data);
        $this->template->render();
    }

    public function index(){
        $this->load->library('table');
        $this->table->set_heading(array_slice($this->fields_table, 1));
        $this->table->set_template($this->getTemplate());
        $data['tabla'] = $this->table->generate($this->usuario_model->getUsuarios(array_slice($this->fields_table, 1)), strtolower(__CLASS__), true);
        $this->template->write_view('content', 'content/usuario', $data);
        $this->template->render();
    }

    public function borrar($codigo = ''){
        $this->usuario_model->borrar($codigo);
        redirect('usuario');
    }
    
    public function agregar(){
        $this->load->library('table');
        $this->load->library('form_creator');

        $this->form_creator->setTabla(strtolower(__CLASS__));
        $hidden  = $this->form_creator->pintaCampo(array('field' => "p_accion", 'type' => 'HDN', 'value' => 'C'));
        $hidden .= $this->form_creator->pintaCampo(array('field' => "usu_empresa", 'type' => 'HDN', 'value' => $this->session->userdata('idusuario')));
        $campos = array();
        for($x = 1; $x < count($this->fields_form); $x++){
            if($this->fields_form[$x] == 'usu_idi_spanish'){
                $campos[] = '';
                $campos[] = lang('idiomas_que_dominas');
                $campos[] = '';
                $campos[] = '';
            }
            
            $campos[] = lang($this->fields_form[$x]);
            $campos[] = $this->switch_comun($this->fields_form[$x]);
        }

        $new_list = $this->table->make_columns($campos, 4);
        $data['tabla'] = $hidden.$this->table->generate($new_list, strtolower(__CLASS__));
        $this->template->write_view('content', 'content/usuario_ce', $data);
        $this->template->render();
    }

    public function editar($indice = ''){
        $this->load->library('table');
        $this->load->library('form_creator');

        $this->renderRolPass();
        $usuario = $this->usuario_model->getUsuarios($this->fields_form, $indice);
        $this->form_creator->setTabla(strtolower(__CLASS__));
        $row = $usuario->row_array();
        $hidden  = $this->form_creator->pintaCampo(array('field' => $this->fields_form[0], 'type' => 'HDN', 'value' => $row[$this->fields_form[0]]));
        $hidden .= $this->form_creator->pintaCampo(array('field' => "p_accion", 'type' => 'HDN', 'value' => 'E'));
        $hidden .= $this->form_creator->pintaCampo(array('field' => "p_campos", 'type' => 'HDN', 'value' => $indice));
        $campos = array();
        for($x = 1; $x < count($this->fields_form); $x++){
            if($this->fields_form[$x] == 'usu_idi_spanish'){
                $campos[] = '';
                $campos[] = lang('idiomas_que_dominas');
                $campos[] = '';
                $campos[] = '';
            }
                
            $campos[] = lang($this->fields_form[$x]);
            $campos[] = $this->switch_comun($this->fields_form[$x], $row[$this->fields_form[$x]]);
        }
        $new_list = $this->table->make_columns($campos, 4);
        $data['tabla'] = $hidden.$this->table->generate($new_list, strtolower(__CLASS__));
        $this->template->write_view('content', 'content/usuario_ce', $data);
        $this->template->render();
    }

    public function guardar(){
        $this->load->helper('string');
        $this->load->library('loginlib');

        $accion = $_POST['p_accion'][0];
        $random_string = random_string('alnum', 8);
        $parametros = array();

        for($z = 1; $z < count($this->validate_fields); $z++){
            $this->form_validation->set_rules($this->fields_form[$z].'[]', 'lang:'.$this->fields_form[$z], $this->validate_fields[$z]);
        }
        if($accion == 'R'){
            $this->form_validation->set_rules('captcha', 'captcha', 'required|matches[imagen]');
            $this->form_validation->set_rules('usu_password', 'lang:usu_password', 'required|matches[repetida]');
        }
        if($this->form_validation->run() == FALSE){
            if($accion == 'R'){
                $this->registro();
                return;
            }else if($accion == 'C'){
                redirect('usuario/agregar');
            }else if($accion == 'E'){
                $this->editar($_POST['p_campos'][0]);
                return;
            }
	}
        foreach ($this->input->post() as $key => $value) {
            for($i = 0; $i < count($value); $i++){
                if(strpos($key, "usu") !== false){
                    if($value[$i] != ''){
                        if(strpos($key, "usu_password") !== false){
                            if($accion == 'C'){
                                $parametros[$i][$key] = md5($random_string);
                                $parametros[$i]["usu_rol"] = 4;
                            }else if($accion == 'R'){
                                $parametros[$i][$key] = md5($value[$i]);
                                $password = $value[$i];
                                $parametros[$i]["usu_rol"] = 3;
                            }
                        }else if(strpos($key, "usu_idi_") !== false){
                            if($value[$i] == 'on'){
                                $parametros[$i][$key] = 'S';
                            }else{
                                $parametros[$i][$key] = 'N';
                            }
                        }else{
                            $parametros[$i][$key] = $value[$i];
                        }
                    }
                }
                
            }
        }
        if($accion == 'C'){
            $this->usuario_model->guardar($parametros[0]);
            $this->session->set_flashdata('message', lang('successfully_created'));
            //fEnviaMailCreaUsuario('pepmahou@hotmail.com', 'Prueba', 'Texto de prueba');
            redirect('usuario', 'refresh');
        }else if($accion == 'R'){
            $this->usuario_model->guardar($parametros[0]);
            $this->loginlib->login($parametros[0]['usu_login'], $password);
            redirect('');
        }else if($accion == 'E'){
            $this->usuario_model->actualizar($parametros[0]);
            redirect('usuario', 'refresh');
        }
    }
    
    function switch_comun($field = '', $value = ''){
        $this->load->helper('directory');
        $this->load->helper('settings');
        switch ($field) {
            case 'usu_idusuario':
                return $this->form_creator->pintaCampo(array('field' => $field, 'type' => 'HDN', 'value' => $value));
                break;
            case 'usu_idioma':
                return $this->form_creator->pintaCampo(array('field' => 'usu_idioma',
                                                             'type' => 'SEL',
                                                             'code' => generaOptionsCombo(directory_map('./application/language/', 1), $value)
                                                       ));
                break;
            case 'usu_rol':
                return $this->form_creator->pintaCampo(array('field' => 'usu_rol',
                                                             'type' => 'SEL',
                                                             'code' => generaOptionsCombo($this->usuario_model->getRols(), $value)
                                                       ));
                break;
            case 'usu_password':
                return $this->form_creator->pintaCampo(array('field' => 'usu_password', 'type' => 'PWD', 'value' => $value));
                break;
            case 'repetida':
                return $this->form_creator->pintaCampo(array('field' => 'repetida', 'type' => 'PWD2', 'value' => $value));
                break;
            default:
                return $this->form_creator->pintaCampo(array('field' => $field, 'value' => $value));
        }
    }
}

?>
